import urlConstants from '@/constants/urlConstants';
import useIntlCustom from '@/hooks/useIntlCustom';
import commonService from '@/services/common';
// import store from '@/store';
import { SmartBreadcrumb } from '@/components';
import { getOrgTreeList } from '@/services/system';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Form, message, Modal } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import AddOrgModal from './components/AddOrgModal';
import OrgDetailCard from './components/OrgDetailCard';
import OrgTree from './components/OrgTree';
import SearchInput from './components/SearchInput';
import styles from './index.css';
// 定义组织节点类型
interface OrgNode {
  title: string;
  key: string;
  children?: OrgNode[];
  originalData?: any; // 保留原始数据
}

const OrgPage: React.FC = () => {
  const { translate } = useIntlCustom();
  // const [userState, userDispatchers] = store.useModel('user');
  const prefix = 'systemManage';
  // 状态管理
  const [selectedKey, setSelectedKey] = useState<string>('');
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [orgParentDetail, setOrgParentDetail] = useState({});
  const [detail, setDetail] = useState({});
  const [editForm] = Form.useForm();
  const [orgtreeData, setOrgTreeData] = useState<OrgNode[]>([]);

  // 使用 useMemo 将 orgtreeData 转换为 antd Tree 结构
  const processedTreeData = useMemo<OrgNode[]>(() => {
    // 辅助函数用于递归处理树形数据
    const processNode = (node: any, parentKey: string = ''): OrgNode => {
      const currentKey = parentKey ? `${parentKey}-${node.departmentId}` : node.departmentId;
      return {
        title: node.departmentName,
        key: currentKey,
        // 保留原始数据，方便后续使用
        originalData: node,
        children: node.children ? node.children.map((child: any) => processNode(child, currentKey)) : undefined,
      };
    };

    if (orgtreeData && orgtreeData.length > 0) {
      return orgtreeData.map((node) => processNode(node));
    }
    // 如果没有动态数据，返回空数组
    return [];
  }, [orgtreeData]);

  // 处理树节点选择
  const handleTreeSelect = useCallback(
    (keys: React.Key[]) => {
      const selectedKey = keys[0]?.toString();
      setSelectedKey(selectedKey);
      setIsEditing(false);
      const findNodeDetail = (nodes: any[], searchKey: string): any => {
        const buildNodeKey = (currentNode: any, parentPath: string = ''): any => {
          const currentKey = parentPath ? `${parentPath}-${currentNode.departmentId}` : currentNode.departmentId;
          if (currentKey === searchKey) {
            return {
              departmentId: currentNode.departmentId,
              departmentName: currentNode.departmentName,
              parentId: currentNode.parentId,
              count: currentNode.memberCount,
            };
          }
          // 递归检查子节点
          if (currentNode.children) {
            for (const child of currentNode.children) {
              const result = buildNodeKey(child, currentKey);
              if (result) return result;
            }
          }
          return null;
        };

        // 遍历所有根节点
        for (const node of nodes) {
          const result = buildNodeKey(node);
          if (result) return result;
        }

        // 如果没找到，返回 null 而不是空对象
        return null;
      };

      const newDetail = findNodeDetail(orgtreeData, selectedKey);
      // 只有找到数据时才更新
      if (newDetail) {
        setDetail(newDetail);
        editForm.setFieldsValue(newDetail);
      }
    },
    [orgtreeData, editForm],
  );

  // 搜索树节点
  const searchInTree = useCallback((nodes: OrgNode[], searchText: string): string[] => {
    const matchedKeys: string[] = [];
    const traverse = (nodeList: OrgNode[]) => {
      nodeList.forEach((node) => {
        if (node.title?.toLowerCase().includes(searchText?.toLowerCase())) {
          matchedKeys.push(node.key);
        }
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(nodes);
    return matchedKeys;
  }, []);

  // 处理搜索
  const handleSearch = useCallback(
    (value: string) => {
      if (value) {
        const matchedKeys = searchInTree(processedTreeData, value);
        setExpandedKeys(matchedKeys);
        setAutoExpandParent(true);
        if (matchedKeys.length > 0) {
          setSelectedKey(matchedKeys[0]);
        }
      } else {
        // 清空搜索时，收起所有节点
        setExpandedKeys([]);
        setAutoExpandParent(false);
        setSelectedKey('');
      }
    },
    [processedTreeData, searchInTree],
  );

  // 初始化
  useEffect(() => {
    getTableData();
    // !Array.isArray(userState.orgList) && userDispatchers.getOrgList();
  }, []);

  // 数据加载后自动展开第一层
  useEffect(() => {
    if (processedTreeData.length > 0) {
      // 自动展开第一层节点
      const firstLevelKeys = processedTreeData.map((node) => node.key);
      setExpandedKeys(firstLevelKeys);
      // 自动选中第一个节点
      if (firstLevelKeys.length > 0 && !selectedKey) {
        setSelectedKey(firstLevelKeys[0]);
        handleTreeSelect(firstLevelKeys);
      }
    }
  }, [processedTreeData]);

  // 逻辑处理
  const getTableData = async () => {
    setLoading(true);
    try {
      const res: any = await getOrgTreeList();
      console.log(res, 'res');
      Array.isArray(res) && setOrgTreeData(res);
    } catch (error) {
      setOrgTreeData([]);
      setLoading(false);
    } finally {
      setLoading(false);
    }
  };

  // 处理树节点展开
  const handleTreeExpand = useCallback((keys: React.Key[]) => {
    setExpandedKeys(keys.map((key) => key.toString()));
    setAutoExpandParent(false);
  }, []);

  // 处理编辑操作
  const handleEdit = () => {
    setIsEditing(true);
    // 确保表单数据与当前 detail 同步
    if (detail && Object.keys(detail).length > 0) {
      editForm.setFieldsValue(detail);
    }
  };

  // 处理保存操作
  const handleSave = () => {
    editForm.validateFields().then(async (values) => {
      setDetail({ ...detail, ...values });
      setIsEditing(false);
      const res: any = await commonService.fetchCommonUpdateData({
        url: urlConstants.ORGANIZATION_MANAGE.EDIT,
        params: { ...detail, ...values },
      });
      if (res.code === 200) {
        message.success('保存成功');
        getTableData();
      }
    });
  };

  // 处理取消操作
  const handleCancel = () => {
    setIsEditing(false);
    editForm.setFieldsValue(detail);
  };

  // 在组件内部添加处理加号按钮点击的函数
  const handleAddClick = (node: any) => {
    setAddModalVisible(true);
    // 使用原始数据中的 departmentId
    const parentId = node.originalData?.parentId;
    setOrgParentDetail({ key: parentId, title: node.title });
  };

  // 处理删除操作
  const handleDelete = useCallback(
    (detail: any) => {
      Modal.confirm({
        title: translate('common', 'confirmDelete'),
        icon: <ExclamationCircleOutlined />,
        async onOk() {
          // 模拟API调用
          const res: any = await commonService.fetchCommonUpdateData({
            url: urlConstants.ORGANIZATION_MANAGE.DELETE,
            params: { departmentId: detail.departmentId },
          });
          if (res.code === 200) {
            getTableData();
            message.success(translate('common', 'deleteSuccess'));
          }
        },
      });
    },
    [translate],
  );

  // 新增弹窗取消
  const handleAddCancel = () => {
    setOrgParentDetail({});
    setAddModalVisible(false);
  };

  // 新增弹窗提交 - 修改为async函数
  const handleAddOrg = useCallback(async (values: any) => {
    // 模拟API调用
    const res: any = await commonService.fetchCommonUpdateData({
      url: urlConstants.ORGANIZATION_MANAGE.CREATE,
      params: { ...values },
    });
    if (res.code === 200) {
      message.success('新增成功');
      getTableData();
      setAddModalVisible(false);
      setOrgParentDetail({});
    }
  }, []);

  return (
    <div className={styles.container}>
      <div className={`app-block m-tb-0 ${styles.routerBar}`}>
        <SmartBreadcrumb />
      </div>
      <div className={styles.content}>
        {/* 左侧树形菜单 */}
        <div className={styles.sidebar}>
          <div className={styles.treeHeader}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div className={styles.treeTitle}>{translate(prefix, 'orgTree')}</div>
              <Button type="primary" onClick={() => setAddModalVisible(true)}>
                {translate(prefix, 'addOrg')}
              </Button>
            </div>
            <SearchInput
              className={styles.searchInput}
              placeholder={translate(prefix, 'searchOrgPlaceholder')}
              onSearch={handleSearch}
              style={{ marginTop: 12 }}
            />
          </div>
          <OrgTree
            treeData={processedTreeData}
            selectedKey={selectedKey}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onSelect={handleTreeSelect}
            onExpand={handleTreeExpand}
            onAddClick={handleAddClick}
          />
        </div>
        {/* 新增机构弹窗 */}
        <AddOrgModal
          orgParentDetail={orgParentDetail}
          visible={addModalVisible}
          onCancel={handleAddCancel}
          onOk={handleAddOrg}
          loading={loading}
          prefix={prefix}
          orgTreeData={orgtreeData}
        />
        {/* 右侧详情 */}
        <div className={styles.orgDetailContainer}>
          <div className={`${styles.orgDetailTitle} ${styles.treeTitle}`}>{translate(prefix, 'orgDetail')}</div>
          <div className={styles.detail}>
            <OrgDetailCard
              detail={detail}
              isEditing={isEditing}
              editForm={editForm}
              onEdit={handleEdit}
              onSave={handleSave}
              onCancel={handleCancel}
              onDelete={() => handleDelete(detail)}
              loading={loading}
              translate={translate}
              prefix={prefix}
              orgTreeData={orgtreeData}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default OrgPage;
